const axios = require('axios');
const fs = require('fs');
const path = require('path');
const get_token = require('./getAccessToken');

async function main(code) {
  var token = require('./token.json');
  if(!token.access_token || Date.now() - token.time > token.expires_in) {
    token = await get_token();
    token.time = Date.now();
    fs.writeFileSync(path.join(__dirname, './token.json'), JSON.stringify(token));
  }
  const url = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${token.access_token}`;
  return new Promise((resolve, reject) => {
    axios.post(url, { code }).then(res => {
      if(res.data.phone_info.purePhoneNumber) {
        resolve(res.data.phone_info);
      } else reject(res.data);
    }).catch(err => {
      reject(err);
    });
  })
}

module.exports = main;